import Taro from '@tarojs/taro';
import api from '@doctorwork/utils/network';
import { storage } from '@doctorwork/saga';
import { effects } from 'dva-core/saga';
import Payment from './payment';


export { action, delay } from '../action';

const noop = () => {};

export default {
    Payment
};

export { Payment };

export const loading = {
    show: noop,
    hide: noop
};

const sysInfo = {
    model: '',
    brand: '',
    system: 'iOS',
    platform: 'ios',
    language: 'cn',
    statusBarHeight: 40
};

export const getSystemInfoSync = () => {
    return sysInfo;
};

export const getSystemInfo = ({ success }) => {
    success({
        res: sysInfo
    });
};
/* @FIXME: 需要提取出来单独处理 */
export const stopPullDownRefresh = Taro.stopPullDownRefresh;

export const setNavigationBarTitle = Taro.setNavigationBarTitle;

export const createSelectorQuery = Taro.createSelectorQuery;

window.getCurrentPages = () => {
    return Taro.getCurrentPages().filter(Boolean);
};

export class Authientication {
    constructor(options){
        this.options = options;
    }

    *auth() {
        // 1 . 存储当前页面地址
        yield effects.put.resolve(storage.set('redirect', window.location.href));
        // 2 . 拼接静默登录URL 
        /** 
        const locationUrl = location.href.split('#');
        const redirectUrl = encodeURIComponent(
            `${locationUrl[0]}#/base/_login/index`
        );
        */
        //@FIXME: 目前用的 hash 为路由
        // 后续换到 history 需要做兼容
        const redirectUrl = window.location.href.replace(window.location.hash, '#'+this.options.webRedirectPage);
        const url = `${this.options.webAuthPage}?appId=${this.options.appId}&redirectUrl=${encodeURIComponent(redirectUrl)}&appName=${this.options.appName}`;
            
        setTimeout(() =>{
            window.location.replace(url);
        }, 200);
    }
}


// 本地BlobUrl解码，返回base64
const decodeImgBlob = (url) => new Promise( (resolve) => {
    const xhr = new XMLHttpRequest();
    const fileReader = new FileReader()
    let fileBlob
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function(e) {
        if (this.status == 200) {
            fileBlob = this.response
            fileReader.readAsDataURL(this.response)
        }
    };
    xhr.send();
    fileReader.onload = (e) => {
        resolve({
            fileBlob,
            dataUrl: e.srcElement.result
        })
    }
})
// @TODO 用的base64上传
export const uploadFile = (options = {}) => new Promise( (resolve) => {
    if(!options.filePath) return

    const { filePath, url, ...rest } = options
    const [ baseUrl, token ] = url.split('?token=')

    const formData = new FormData()
    
    // formData.append('upload_token', token)
    formData.append('token', token)

    decodeImgBlob(options.filePath).then( ({fileBlob, dataUrl}) => {
        formData.append('file', fileBlob)
        const size = fileBlob.size
        const base64 = dataUrl.replace('data:text/html;base64,', '')
        Taro.request({
            method: 'POST',
            header: {
                // 'Content-Type': `application/octet-stream`,
                // 'Authorization': `UpToken ${token}`
            },
            //url: `http://up-z2.qiniup.com/putb64/${size}`,
            url: baseUrl,
            data: formData
        })
            .then(res => {
                console.log(120 ,res)
                resolve({
                    data: JSON.stringify(res.data)
                })
            })
    })
})



